// 太阳能发电系统监控界面 - 仪表盘页面脚本

// 初始化Vue应用
const vm = new Vue({
  el: "#app",
  data: {
    // 从全局数据获取
    isDeviceOn: appData.isDeviceOn,
    showPowerDialog: appData.showPowerDialog,
    pendingPowerState: appData.pendingPowerState,
    lastUpdateTime: appData.lastUpdateTime,
    showAlert: appData.showAlert,
    alertMessage: appData.alertMessage,
    statusData: { ...appData.statusData },

    // 仪表盘特定数据
    summaryData: [
      {
        icon: "fas fa-bolt",
        title: "今日发电",
        value: appData.powerData.todayGeneration,
        unit: "度",
        secondary: `目标: ${appData.powerData.dailyTarget}度`,
      },
      {
        icon: "fas fa-calendar-alt",
        title: "本月累计",
        value: appData.powerData.monthlyGeneration,
        unit: "度",
        secondary: `同比上周 ${appData.powerData.monthlyTrend > 0 ? "+" : ""}${
          appData.powerData.monthlyTrend
        }%`,
      },
      {
        icon: "fas fa-piggy-bank",
        title: "预估节省",
        value: appData.distributionData.savingAmount,
        unit: "元",
        secondary: "基于当前电价计算",
      },
    ],

    // 刷新计时器
    refreshInterval: null,
  },
  computed: {
    // 状态卡片样式计算
    voltageCardClass() {
      return {
        warning: this.statusData.voltageStatus === "warning",
        danger: this.statusData.voltageStatus === "danger",
      };
    },
    temperatureCardClass() {
      return {
        warning: this.statusData.temperatureStatus === "warning",
        danger: this.statusData.temperatureStatus === "danger",
      };
    },
    efficiencyCardClass() {
      return {
        warning: this.statusData.efficiencyStatus === "warning",
        danger: this.statusData.efficiencyStatus === "danger",
      };
    },
  },
  methods: {
    // 更新最后更新时间
    updateLastUpdateTime() {
      this.lastUpdateTime = appMethods.updateLastUpdateTime();
    },

    // 切换电源状态
    togglePower() {
      appMethods.togglePower();
      this.showPowerDialog = appData.showPowerDialog;
      this.pendingPowerState = appData.pendingPowerState;
    },

    // 取消电源操作
    cancelPowerAction() {
      appMethods.cancelPowerAction();
      this.showPowerDialog = appData.showPowerDialog;
    },

    // 确认电源操作
    confirmPowerAction() {
      appMethods.confirmPowerAction();
      this.isDeviceOn = appData.isDeviceOn;
      this.showPowerDialog = appData.showPowerDialog;

      // 更新UI和数据
      this.updateDeviceStatus();
      this.updateLastUpdateTime();

      // 如果开启设备，启动数据自动刷新
      if (this.isDeviceOn) {
        this.startAutoRefresh();
      } else {
        // 停止自动刷新
        this.stopAutoRefresh();
      }
    },

    // 更新设备状态
    updateDeviceStatus() {
      console.log(`设备状态已切换为: ${this.isDeviceOn ? "开启" : "关闭"}`);

      // 如果设备已关闭，显示提示信息
      if (!this.isDeviceOn) {
        this.showSystemAlert("设备已关闭，数据记录已停止");
      }
    },

    // 显示系统报警
    showSystemAlert(message) {
      appMethods.showSystemAlert(message);
      this.showAlert = appData.showAlert;
      this.alertMessage = appData.alertMessage;
    },

    // 确认报警
    acknowledgeAlert() {
      appMethods.acknowledgeAlert();
      this.showAlert = appData.showAlert;
    },

    // 检查异常状态
    checkAbnormalStatus() {
      // 模拟电压变化
      this.statusData.voltage = 220 + Math.floor(Math.random() * 20);

      // 电压状态判断
      if (this.statusData.voltage < 210 || this.statusData.voltage > 250) {
        this.statusData.voltageStatus = "danger";
        this.showSystemAlert(`电压异常: ${this.statusData.voltage}V`);
      } else if (
        this.statusData.voltage < 220 ||
        this.statusData.voltage > 240
      ) {
        this.statusData.voltageStatus = "warning";
      } else {
        this.statusData.voltageStatus = "normal";
      }

      // 模拟温度变化
      const hourFactor = Math.sin(((new Date().getHours() - 6) / 12) * Math.PI);
      const baseTemp = 40 + hourFactor * 10;
      this.statusData.temperature = Math.floor(baseTemp + Math.random() * 15);

      // 温度状态判断
      if (this.statusData.temperature > 60) {
        this.statusData.temperatureStatus = "danger";
        this.showSystemAlert(`组件温度过高: ${this.statusData.temperature}°C`);
      } else if (this.statusData.temperature > 50) {
        this.statusData.temperatureStatus = "warning";
      } else {
        this.statusData.temperatureStatus = "normal";
      }

      // 模拟逆变器效率变化
      this.statusData.efficiency = 95 + Math.random() * 3;
      this.statusData.efficiency = parseFloat(
        this.statusData.efficiency.toFixed(1)
      );

      // 效率状态判断
      if (this.statusData.efficiency < 93) {
        this.statusData.efficiencyStatus = "danger";
        this.showSystemAlert(`逆变器效率异常: ${this.statusData.efficiency}%`);
      } else if (this.statusData.efficiency < 95) {
        this.statusData.efficiencyStatus = "warning";
      } else {
        this.statusData.efficiencyStatus = "normal";
      }

      // 更新全局数据
      Object.assign(appData.statusData, this.statusData);
    },

    // 更新发电数据
    updatePowerData() {
      if (!this.isDeviceOn) return;

      // 更新今日发电量（随机增加）
      const increment = Math.random() * 0.2;
      const newValue = parseFloat(
        (this.summaryData[0].value + increment).toFixed(1)
      );
      this.summaryData[0].value = newValue;

      // 如果超过目标，调整目标
      if (newValue > parseFloat(this.summaryData[0].secondary.split(": ")[1])) {
        const newTarget = parseFloat(
          (
            parseFloat(this.summaryData[0].secondary.split(": ")[1]) + 1
          ).toFixed(1)
        );
        this.summaryData[0].secondary = `目标: ${newTarget}度`;
      }

      // 更新预估节省金额
      this.summaryData[2].value = parseFloat((newValue * 0.6).toFixed(1));

      // 检查异常状态
      this.checkAbnormalStatus();

      // 更新全局数据
      appData.powerData.todayGeneration = newValue;
    },

    // 启动自动刷新
    startAutoRefresh() {
      // 每30秒刷新一次数据
      this.refreshInterval = setInterval(() => {
        this.updatePowerData();
        this.updateLastUpdateTime();
      }, appData.settingsData.refreshInterval * 1000);

      // 立即更新一次
      this.updatePowerData();
    },

    // 停止自动刷新
    stopAutoRefresh() {
      if (this.refreshInterval) {
        clearInterval(this.refreshInterval);
        this.refreshInterval = null;
      }
    },
  },
  mounted() {
    // 确保从localStorage加载最新设置
    appMethods.loadSettingsFromStorage();

    // 更新初始时间
    this.updateLastUpdateTime();

    // 启动自动刷新
    if (this.isDeviceOn && appData.settingsData.autoRefresh) {
      this.startAutoRefresh();
    }

    // 模拟可能的系统异常（10%概率）
    if (Math.random() < 0.1) {
      setTimeout(() => {
        this.showSystemAlert("检测到电网连接不稳定，请检查连接");
      }, 2000);
    }
  },
  beforeDestroy() {
    // 清理定时器
    this.stopAutoRefresh();
  },
});
